require "Common/define"
require "Logic/Config"
require "Common/functions"

RedDotsSummonHandler ={};
local this = RedDotsSummonHandler;

local drawPoolConfig = nil;

function RedDotsSummonHandler.init()
    CloseEvent(Config.EventType.Fresh_Bag,this.update);
    CloseEvent(Config.EventType.Fresh_Currency,this.update);
    CloseEvent(Config.EventType.Fresh_Free_Summon,this.update);

    ListenEvent(Config.EventType.Fresh_Bag,this.update);
    ListenEvent(Config.EventType.Fresh_Currency,this.update);
    ListenEvent(Config.EventType.Fresh_Free_Summon,this.update);

    if drawPoolConfig == nil then
        drawPoolConfig = G.dataTable["t_drawpool"];
    end

    return this;
end


--参数1：卡池Id， nil为所有检查所有
--参数2：抽卡数量（单抽/10连之类） table
function RedDotsSummonHandler.getFlag(...)
    local flag = Config.RedDotsFlagState.None;
    if logicMgr.FuncOpenManager.isOpen(Config.FuncOpenType.Draw,false) then
        local poolId,count = ...;
        if poolId~=nil then
            flag = this.getFlagByPool(poolId,count);
        else
            for key, value in pairs(drawPoolConfig) do
                flag = this.getFlagByPool(value.f_DrawPoolID,count);
                if flag == Config.RedDotsFlagState.Needful then
                    break;
                end
            end
        end
    end
    return flag;
end

function RedDotsSummonHandler.getFlagByPool(poolId, checkList)
    -- 常规卡池免费单抽
    if tonumber(poolId) == 1 and table.contains(checkList, 1) and logicMgr.FuncOpenManager.isOpen(Config.FuncOpenType.FreeSummon, false) then
        if drawHandler.getNormalSummonFreeLeftTime() <= 0 then
            return Config.RedDotsFlagState.Needful
        elseif not table.contains(checkList, 10) then
            return Config.RedDotsFlagState.None
        end
    end

    -- 此处修改为只检查10连
    local count = 10
    local flag = Config.RedDotsFlagState.None;
    if count + logicMgr.HeroManager.getDrawTodayCount(poolId) > dataTable.getGlobalInt(616) then
        return flag;
    end

    local cg = drawPoolConfig[tostring(poolId)];
    if cg~=nil then
        local cost = nil;
        if  count ==10 and cg.f_10DrawsConsume ~= nil and #cg.f_10DrawsConsume>0 then
           cost = decodeJsonStrToTabel(cg.f_10DrawsConsume);
        elseif (count == nil or count == 1) and cg.f_1DrawConsume~=nil and #cg.f_1DrawConsume>0 then
            --cost = decodeJsonStrToTabel(cg.f_1DrawConsume);
            flag = Config.RedDotsFlagState.None;
            return flag;
        end

        if cost~=nil then
            if logicMgr.ItemManager.getBagNumByTableID(cost[1])>=cost[2] then
                flag = Config.RedDotsFlagState.Needful;
            end
            if tonumber(poolId) == 6 and logicMgr.ItemManager.getBagNumByTableID(200004) <= 0 then
                flag = Config.RedDotsFlagState.None;
            end
        end
    end
    return flag;
end

function RedDotsSummonHandler.update()
    RedDotsManager.addBroadcast(Config.RedDotsType.Summon);
end